package com.thinvent.remotepassword.controller;

import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.thinvent.remotepassword.service.ExtractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("/extract")
public class ExtractController extends ApiController {

    private String uploadPath = "/data/static_files/";

    @Autowired
    private ExtractService deployService;

    /**
     * 文档知识提取
     * @param id
     * @return
     */
    @GetMapping("/doc")
    public R selectOne(@RequestParam String id) {
        return success(this.deployService.extract(id));
    }

    @PostMapping("/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        // 校验文件名称是否重复
        String directoryPath = uploadPath;
        try {
            Set<String> filenames = getFilenames(directoryPath);

            // 检查是否存在重复的文件名
            if (hasDuplicates(filenames)) {
                throw new RuntimeException("文件名重复!");
            } else {
                System.out.println("没有重复的文件名。");
            }
        } catch (IOException e) {
            System.err.println("读取目录时发生错误: " + e.getMessage());
        }
        try {
            if (!file.isEmpty()) {
                byte[] bytes = file.getBytes();
                Path path = Paths.get(uploadPath + file.getOriginalFilename());
                Files.write(path, bytes);
                return success(uploadPath + file.getOriginalFilename());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success(uploadPath + file.getOriginalFilename());
    }

    private static Set<String> getFilenames(String directoryPath) throws IOException {
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            throw new IllegalArgumentException("指定的路径不存在或不是一个目录: " + directoryPath);
        }

        Set<String> filenames = new HashSet<>();
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                filenames.add(file.getName());
            }
        }
        return filenames;
    }

    private static boolean hasDuplicates(Set<String> filenames) {
        return filenames.size() != new HashSet<>(filenames).size();
    }
}
